package client.setup;

import client.Identifier;
import communication.SSLProtocolSocketFactory;
import constans.ConfigurationConstans;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import utils.ObjectUtils;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class IdentifierRetriver extends SwingWorker<Boolean, Void> {



    private final String   URL_REGISTRY = "https://t29.tomba.fccn.pt:8443/rarc/registry";

    private String           email;
    private String           name;
    private Logger         logger;
    private boolean       newUser;
    private String           zipcode;
    private String           location;

    private JButton         nextButton;
    private JButton         backButton;
    private JButton         cancelButton;
    private String           password;
    private JProgressBar   progressBar;
    private ResourceBundle rb;
    private JLabel         statuslabel;
    private JLabel         sLabel;
    private JPanel         configurationPanel;
    private JPanel         setupPanel;
    



    public IdentifierRetriver(String email, String password, String name, boolean newUser,String zipcode, String location,
            JPanel setupPanel, JPanel configurationPanel, JLabel sLabel, JProgressBar progressBar, JLabel statuslabel,
            JButton backButton, JButton nextButton, JButton cancelButton, ResourceBundle rb, Logger logger) {
        this.email       = email;
        this.password    = password;
        this.name = name;
        this.newUser     = newUser;
        this.zipcode = zipcode;
        this.location = location;
        
        this.setupPanel = setupPanel;
        this.configurationPanel = configurationPanel;
        this.progressBar = progressBar;
        this.statuslabel = statuslabel;
        this.sLabel      = sLabel;
        this.nextButton  = nextButton;
        this.backButton  = backButton;
        this.cancelButton = cancelButton;
        this.rb          = rb;
        this.logger      = logger;
    }


    @Override
    protected Boolean doInBackground()
            throws Exception {
        return new Boolean(getIdentifier());
    }



    private boolean getIdentifier() {

         
        sLabel.setText(rb.getString("SetupMainSetupLabel1"));

         
        Protocol easyhttps = new Protocol("https", new SSLProtocolSocketFactory(),8443);
        Protocol.registerProtocol("https", easyhttps);
        
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setParameter("http.useragent", "rarc-setup");
        httpclient.getParams().setParameter("http.connection.timeout", new Integer(5000));
        
        PostMethod method = new PostMethod(URL_REGISTRY);
        method.addParameter("new-user", String.valueOf(newUser));
        method.addParameter("email", email);
        method.addParameter("password", password);
        method.addParameter("name", name);
        method.addParameter("zipcode", zipcode);
        method.addParameter("location", location);

         
        progressBar.setValue(1);
        statuslabel.setText(rb.getString("IdentifierRetriverSending"));


         
        int returnCode = HttpStatus.SC_NOT_IMPLEMENTED;

        try {
             
            returnCode = httpclient.executeMethod(method);
        } catch (IOException e) {
            
             
            refreshInterface(false, false,true, rb.getString("IdentifierRetriverServer"));
            setupPanel.setVisible(true);
             
            closeConnection(method);            
             
            logger.log(Level.SEVERE, e.getMessage());
            
            return false;
        }

        if (returnCode != HttpStatus.SC_NOT_IMPLEMENTED) {

             
            Header header      = method.getResponseHeader("status-code");
            int    status_code = Integer.parseInt(header.getValue());

            if (status_code == HttpStatus.SC_OK) {

                 
                progressBar.setValue(2);
                statuslabel.setText(rb.getString("IdentifierRetriverReceiving"));

                byte[]     bytesIdentifer = null;
                Identifier identifier     = null;

                try {
                     
                    bytesIdentifer = method.getResponseBody();
                    identifier     = (Identifier) ObjectUtils.toObject(bytesIdentifer);
                } catch (IOException e) {

                     
                    refreshInterface(false, false,true,e.getMessage());
                    closeConnection(method);
                    logger.log(Level.SEVERE, e.getMessage());

                    return false;

                } catch (ClassNotFoundException e) {
                    
                     
                    refreshInterface(false, false,true,e.getMessage());
                    closeConnection(method);
                    logger.log(Level.SEVERE, e.getMessage());

                    return false;
                    
                }

                 
                progressBar.setValue(3);
                statuslabel.setText(rb.getString("IdentifierRetriverStoring"));

                try {
                    ObjectUtils.store(identifier, ConfigurationConstans.IDENTIFIER_FILENAME);
                } catch (IOException e) {//Problems to store identifier

                     
                    refreshInterface(false, false, true, rb.getString("IdentifierRetriverStoringProblems"));
                    setupPanel.setVisible(true);
                    closeConnection(method);
                    logger.log(Level.SEVERE, e.getMessage());                

                    return false;
                }

                 
                closeConnection(method);                 
                refreshInterface(false, true, false,"");                
                setupPanel.setVisible(false);
                configurationPanel.setVisible(true);

                return true;

            } else if(status_code == HttpStatus.SC_INTERNAL_SERVER_ERROR){//Problems in server
                
                 
                refreshInterface(false, true, false,rb.getString("IdentifierRetriverServerError"));
                setupPanel.setVisible(true);
                 
                closeConnection(method);

                return false;

            } else {
                
                 
                if (newUser) {
                     refreshInterface(true, false, true, rb.getString("IdentifierRetriverEmail"));
                     setupPanel.setVisible(true);
                } else {
                    refreshInterface(true, false, true, rb.getString("IdentifierRetriverLogin"));
                    setupPanel.setVisible(true);
                }

                System.out.println("status_code == HTTP_UNAUTHORIZED");
                System.out.println(setupPanel.isVisible());

                 
                closeConnection(method);

                return false;
            }
        } else {

             
            refreshInterface(false, false, true, rb.getString("IdentifierRetriverServerError"));
            setupPanel.setVisible(true);
             
            closeConnection(method);

            return false;
        }
    }



    private void closeConnection(PostMethod method) {
        if (method != null) {
            method.releaseConnection();
        }      
    }

    
    private void refreshInterface(boolean backEnable, boolean nextEnable,boolean cancelEnable,
            String status){
        
        sLabel.setText("");
        progressBar.setValue(progressBar.getMaximum());

        backButton.setEnabled(backEnable);
        nextButton.setEnabled(nextEnable);
        cancelButton.setEnabled(cancelEnable);
        statuslabel.setText(status);
    }



    
}
